package com.ler.yrmall.order.listener;

import com.alibaba.fastjson.JSON;
import com.ler.yrmall.order.entity.OrderEntity;
import com.ler.yrmall.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author Leron
 */
@Slf4j
@Service
@RocketMQMessageListener(consumerGroup = "order-time-out-group",topic = "order_topic",selectorExpression = "create")
public class OrderTimeoutListener implements RocketMQListener<OrderEntity> {

    @Resource
    private OrderService orderService;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 还要发送订单释放消息
     * 防止以下问题发生
     * 正常情况
     * order -----> 释放
     * ware ------------> 释放
     *
     * 异常情况
     * order ------- 机器卡顿 ---------> 释放
     * ware -------------> 释放
     * @param message
     */
    @Override
    public void onMessage(OrderEntity message) {
        log.info("订单超时关闭:{}", JSON.toJSONString(message));
        orderService.closeOrder(message);
        rocketMQTemplate.syncSend("order_topic:release", MessageBuilder.withPayload(message),3000);
    }
}
